package com.ybg.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.ybg.model.ResponseModel;
import com.ybg.utils.LogUtil;
import com.ybg.utils.YbgException;

/**
 * 集中处理Controller类抛出的异常
 * 
 * @author ningjh
 * @since  2016-07-20
 */
@ControllerAdvice
public class GlobalExceptionHandlerController {
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public ResponseModel handleException(Exception exception, HttpServletRequest request) {
		// 转换异常
		YbgException ybgException = createException(exception);
		
		// 打印错误日志
		printLog(ybgException, request);

		// 返回错误响应
		return createResponse(ybgException);
	}
	
	/***
	 * 把异常转换成奕报告自定义异常
	 * 
	 * @param exception
	 * @return
	 */
	private YbgException createException(Exception exception) {
		if (exception instanceof YbgException) {
			return (YbgException) exception;
		} else {
			return new YbgException(exception);
		}
	}
	
	/**
	 * 创建异常响应类
	 * 
	 * @param exception
	 * @return
	 */
	private ResponseModel createResponse(YbgException exception) {
		ResponseModel responseModel = new ResponseModel();
		responseModel.setCode(exception.getErrorCode());
		responseModel.setMsg(exception.getMessage());
		responseModel.setData(exception.getData());
		return responseModel;
	}
	
	/**
	 * 打印异常日志
	 * 日志格式：{method} {uri} {errorCode} {message} {xxdm} {userId} {自定义日志信息}
	 * 
	 * @param exception
	 */
	private void printLog(YbgException exception, HttpServletRequest request) {
		StringBuilder error = new StringBuilder("{} {} {} {} {} {}");
		
		List<Object> arguments = new ArrayList<Object>();
		arguments.add(request.getMethod());
		arguments.add(request.getRequestURI());
		arguments.add(exception.getErrorCode());
		arguments.add(exception.getMessage());
		arguments.add(request.getAttribute("xxdm"));
		arguments.add(request.getAttribute("userId"));
		
		// 打印自定义日志信息
		String custom = exception.getCustom();
		if (custom != null && custom.length() > 0) {
			error.append(" {}");
			arguments.add(custom);
		}
		
		// 打印异常堆栈
		if (exception.getCause() != null) {
			arguments.add(exception.getCause());
		}
		
		LogUtil.error(error.toString(), arguments.toArray());
	}
}
